import React, {useState, useEffect, forwardRef} from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { message } from 'antd';
import TextArea from "antd/es/input/TextArea";

const RichTextEditor = (props) => {
    const { detail } = props;

    const [editorState, setEditorState] = useState(EditorState.createEmpty());

    useEffect(() => {
        if (detail) {
            const contentBlock = htmlToDraft(detail);
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const newEditorState = EditorState.createWithContent(contentState);
            setEditorState(newEditorState);
        }

        getDetail()
    }, [detail]);

    const handleEditorChange = (editorState) => {
        setEditorState(editorState);
    };

    const getDetail = () => {
        const content = convertToRaw(editorState.getCurrentContent());
        return draftToHtml(content);
    };

    const handleKeyCommand = () => {

    }

    const handleImageUpload = (file) => {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/manage/img/upload');
            const data = new FormData();
            data.append('image', file);
            xhr.send(data);
            xhr.addEventListener('load', () => {
                const response = JSON.parse(xhr.responseText);
                const url = response.data.url;
                resolve({ data: { link: url } });
            });
            xhr.addEventListener('error', () => {
                message.error('Image upload failed');
                reject(new Error('Image upload failed'));
            });
        });
    };

    return (
        <div style={{ border: '1px solid #eee', minHeight: 200 }}>
            <Editor
                editorState={editorState}
                onEditorStateChange={handleEditorChange}
                handleKeyCommand={handleKeyCommand}
                customStylemap={{
                    editor: {
                        padding: '10',
                    },
                }}
                toolbar={{
                    image: { uploadCallback: handleImageUpload, alt: { present: true, mandatory: true } },
                }}
            />

            <TextArea
                value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
                disabled
            />
        </div>
    );
};

export default RichTextEditor;